<?php

namespace adibilis\adminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use adibilis\adminBundle\Entity\Article;
use adibilis\AdminBundle\Entity\NewsComment;
use adibilis\adminBundle\Form\ArticleType;
use JMS\SecurityExtraBundle\Annotation\Secure;
use adibilis\AdminBundle\Form\NewsCommentType;

/**
 * Article controller.
 *
 * @Route("/article")
 */
class ArticleController extends Controller
{
    /**
     * Lists all Article entities.
     *
     * @Route("/", name="article")
     * @Template()
     */
    public function indexAction($page)
    {
        $em = $this->getDoctrine()->getManager();

       // $entities = $em->getRepository('adibilisadminBundle:Article')->findAll();


        $entities = $this->getDoctrine() ->getManager()
        ->getRepository('adibilisadminBundle:Article')
        ->getArticles(3, $page);

        return array(
            'entities' => $entities,
            'page' => $page,
            'nombrePage' => ceil(count($entities)/3)
        );
    }

    /**
     * Finds and displays a Article entity.
     *
     * @Route("/{id}/show", name="article_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('adibilisadminBundle:Article')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Article entity.');
        }

        $deleteForm = $this->createDeleteForm($id);


        $repository = $this->getDoctrine()
                             ->getManager()
                             ->getRepository('adibilisadminBundle:NewsComment');
         
          // On récupère l'entité correspondant à l'id $id
          $comments = $repository->findByArticle($id, array('date' => 'asc'));

          $nbComments = count($comments);



          // AJOUT COMMENTAIRE...

          $comment = new NewsComment();
          $comment->setUser($this->get('security.context')->getToken()->getUser());
          $comment->setArticle($entity);
          
         
            // On crée le formulaire grâce à l'ArticleType
            $form = $this->createForm(new \adibilis\adminBundle\Form\NewsCommentType(), $comment);
         
            // On récupère la requête
            $request = $this->getRequest();
         
            // On vérifie qu'elle est de type POST
            if ($request->getMethod() == 'POST') {

              $form->bind($request);

              if ($form->isValid()) {

                $em = $this->getDoctrine()->getManager();
                $em->persist($comment);
                $em->flush();


                // On définit un message flash
                $this->get('session')->getFlashBag()->add('info', 'Commentaire bien ajouté');
         
                // On redirige vers la page de visualisation de l'article nouvellement créé
                return $this->redirect($this->generateUrl('article_show', array('id' => $entity->getId())));
              }
            }

            //FIN Ajout de commentaire



        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
            'comments'  => $comments,
            'nbComments' => $nbComments,
            'form' => $form->createView()
        );
    }




    /**
     * Displays a form to create a new Article entity.
     *
     * @Route("/new", name="article_new")
     * @Template()
     * @Secure(roles="ROLE_ADMIN")
     */
    public function newAction()
    {
        $entity = new Article();
        $form   = $this->createForm(new ArticleType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a new Article entity.
     *
     * @Route("/create", name="article_create")
     * @Method("POST")
     * @Template("adibilisadminBundle:Article:new.html.twig")
     * @Secure(roles="ROLE_ADMIN")
     */
    public function createAction(Request $request)
    {
        $entity  = new Article();
        $form = $this->createForm(new ArticleType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            $this->get('session')->getFlashBag()->add('info', 'Article bien ajouté');

            return $this->redirect($this->generateUrl('article_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Article entity.
     *
     * @Route("/{id}/edit", name="article_edit")
     * @Template()
     * @Secure(roles="ROLE_ADMIN")
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('adibilisadminBundle:Article')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Article entity.');
        }

        $editForm = $this->createForm(new ArticleType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Article entity.
     *
     * @Route("/{id}/update", name="article_update")
     * @Method("POST")
     * @Template("adibilisadminBundle:Article:edit.html.twig")
     * @Secure(roles="ROLE_ADMIN")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('adibilisadminBundle:Article')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Article entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new ArticleType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            $this->get('session')->getFlashBag()->add('info', 'Article bien modifiée');
 

            return $this->redirect($this->generateUrl('article_show', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Article entity.
     *
     * @Route("/{id}/delete", name="article_delete")
     * @Method("POST")
     * @Secure(roles="ROLE_ADMIN")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('adibilisadminBundle:Article')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Article entity.');
            }

            $em->remove($entity);
            $em->flush();
        }


        $this->get('session')->getFlashBag()->add('info', 'Article bien supprimé');


        return $this->redirect($this->generateUrl('article', array('page' => 1)));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }


      /*
      Méthode qui affiche les dernières news selon le nombre donné en paramètre
     */
      public function lastnewsAction($nombre)
      {
        $repository = $this->getDoctrine()->getManager()->getRepository('adibilisadminBundle:Article');

        $liste = $repository->findBy(
          array(),                 // Pas de critère
          array('date' => 'desc'), // On tri par date décroissante
          $nombre,                 // On sélectionne $nombre articles
          0                        // A partir du premier
        );

        return $this->render('adibilisadminBundle:Article:lastnews.html.twig', array(
          'liste_articles' => $liste // C'est ici tout l'intérêt : le contrôleur passe les variables nécessaires au template !
        ));
      }




        /*
        Méthode qui affiche le formulaire d'ajout de commentaire
        */

        public function commentAction()
            {
                $entity = new NewsComment();
                $form   = $this->createForm(new NewsCommentType(), $entity);

                return array(
                    'entity' => $entity,
                    'form'   => $form->createView(),
                );
            }

        /*
        Méthode qui permet la suppression d'un commentaire
        */

        /**
           * @Secure(roles="ROLE_ADMIN")
           */
        public function deletecommentAction($idArticle, $idComment)
            {

                $em = $this->getDoctrine()->getManager();
                $comment = $em->getRepository('adibilisadminBundle:NewsComment')->find($idComment);

                    if (!$comment) {
                        throw $this->createNotFoundException('Unable to find Comment entity.');
                    }

                    $em->remove($comment);
                    $em->flush();

            $this->get('session')->getFlashBag()->add('info', 'Commentaire bien supprimé');
            return $this->redirect($this->generateUrl('article_show', array('id' => $idArticle)));


          }



}
